var map;
var homeControl;
var infoBox;
var idMarker;
var markers = [];

function initialize(idMarcador) {
	
	var localizacao = new google.maps.LatLng(-5.87, -35.22);
	var suporte =  new Boolean();
	// Try W3C Geolocation (Preferred)
	
	if(navigator.geolocation) {
		suporte = true;
		navigator.geolocation.getCurrentPosition(function(position) {
			localizacao = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
		}, function() {
			handleNoGeolocation(suporte);
		});
	}
	// Browser doesn't support Geolocation
	else {
		suporte = false;
		handleNoGeolocation(suporte);
	}

	function handleNoGeolocation(suporte) {
		if (errorFlag == true) {
			localizacao = new google.maps.LatLng(-5.87, -35.22);
		} else {
			localizacao = new google.maps.LatLng(-5.87, -35.22);
		}
	}
	
    var myOptions = {
      zoom: 8,
      center: localizacao,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      sensor: 'true',
      mapTypeControl: false
    }
    
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
    if(idMarcador)
    	idMarker = idMarcador;
    
    fetchPlaces(popularMarcadores);
    
    var dropdown = document.getElementById('filtro');
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(dropdown);
    
    logado = isLogado();
    
    if(logado){
    	// Create the DIV to hold the control and
        // call the HomeControl() constructor passing
        // in this DIV.
        var homeControlDiv = document.createElement('div');
        homeControl = new HomeControl(homeControlDiv, map);

        homeControlDiv.index = 1;
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);
        
        google.maps.event.addListener(map, 'click', onMapClick);
        
//    	create the ContextMenuOptions object
    	var contextMenuOptions={};
    	contextMenuOptions.classNames={menu:'context_menu', menuSeparator:'context_menu_separator'};

    	//	create an array of ContextMenuItem objects
    	var menuItems=[];
    	//menuItems.push({className:'context_menu_item', eventName:'titulo', label:'Compartilhe tudo sobre a \u00e1gua'});
    	//menuItems.push({});
    	menuItems.push({className:'context_menu_item', eventName:'existencia', label:'Exist\u00eancia'});
    	menuItems.push({className:'context_menu_item', eventName:'falta', label:'Falta'});
    	//	a menuItem with no properties will be rendered as a separator

    	menuItems.push({className:'context_menu_item', eventName:'desperdicio', label:'Desperd\u00edcio'});
    	contextMenuOptions.menuItems=menuItems;

    	//	create the ContextMenu object
    	var contextMenu=new ContextMenu(map, contextMenuOptions);

    	//	display the ContextMenu on a Map right click
    	google.maps.event.addListener(map, 'rightclick', function(mouseEvent){
    		if(isLogado()){
    			contextMenu.show(mouseEvent.latLng);
    		}
    	});

    	//	listen for the ContextMenu 'menu_item_selected' event
    	google.maps.event.addListener(contextMenu, 'menu_item_selected', function(latLng,eventName){
    		//	latLng is the position of the ContextMenu
    		//	eventName is the eventName defined for the clicked ContextMenuItem in the ContextMenuOptions
    		var tipo = 1;
    		
    		switch(eventName){
    			case 'existencia':
    				tipo = 1;
    				break;
    			case 'falta':
    				tipo = 2;
    				break;
    			case 'desperdicio':
    				tipo = 3;
    				break;
    		}
    		
    		requestHTML('marcador/iniciarMarcacao',{tipo:tipo,latitude:latLng.lat(),longitude:latLng.lng()},function(data){
    			$('#conteudo-modal').html(data);
    			$('#modal-form').modal('show');
    		});
    		
    	});
    }
    
}


var onMapClick = function(e){
	map.setOptions({ draggableCursor: 'url(http://maps.google.com/mapfiles/openhand.cur), move' });		
	if(homeControl.isEnabled()){
		requestHTML('marcador/iniciarMarcacao',{tipo:1,latitude:e.latLng.lat(),longitude:e.latLng.lng()},function(data){
			$('#conteudo-modal').html(data);
			$('#modal-form').modal('show');
			homeControl.setEnable(false);
		});
	}
}

var isLogado = function(e){
	var logado = false;
	$.ajax({
	    url:'index/isLogado',
	    type:'GET',
	    async:false,
	    success: function(data) {
	    	logado=data.logado;
	    }
	});
	
	return logado;
} 
	
function addMarker(marcador,tipo,id) {
	
	var markerA = new google.maps.Marker({
		position : marcador,
		map : map
	});

	if(tipo == 1)
		markerA.setIcon("images/water.png");
	else if(tipo == 2)
		markerA.setIcon("images/desert.png");
	else
		markerA.setIcon("images/drinkingwater.png");

	markerA.set("id", id);
	markerA.set("tipo", tipo);
	
	google.maps.event.addListener(markerA, 'click', onMarkerClick);
	
	//google.maps.event.trigger(markerA, "click");
	
	return markerA;
}

//fetch Places JSON from /data/places
//loop through and populate the map with markers
var fetchPlaces = function(popularMarcadores) {
	
	jQuery.ajax({
		url : 'marcador/recuperar',
		dataType : 'json',
		async: false,
		success : function(response) {

			if (response.status == 'OK') {
				popularMarcadores(response.marcadores);
			}
		}
	});
}

var popularMarcadores = function(marcadores){
	
	// loop through places and add markers
	for (p in marcadores) {
		var ll = new google.maps.LatLng(marcadores[p].latitude,marcadores[p].longitude);
		marker = addMarker(ll,marcadores[p].tipo,marcadores[p].id)
		markers.push(marker);
		
		if(idMarker == marcadores[p].id){
			map.setCenter(latLng);
			
			var contentString = "Erro ao recuperar conte�do";
			requestAjax({url:'marcador/view',mapa:{id:idMarker}},function(data){
				contentString = data;
				if(infoBox){
					infoBox.setMap(null);
					infoBox = null;
				}
				
				infoBox = new InfoBox({latlng: marker.getPosition(), map: map, conteudo:contentString});
			});
		}
	}
	
	//var markerCluster = new MarkerClusterer(map, markers);
	
}

var onMarkerClick = function() {
	//var infoWindow = new google.maps.InfoWindow;
	var marker = this;
	var latLng = marker.getPosition();
	var id = marker.get("id");
	
	map.setCenter(latLng);
	
	var contentString = "Erro ao recuperar conte�do";
	requestAjax({url:'marcador/view',mapa:{id:id}},function(data){
		contentString = data;
		if(infoBox){
			infoBox.setMap(null);
			infoBox = null;
		}
		infoBox = new InfoBox({latlng: marker.getPosition(), map: map, conteudo:contentString,id:id});
	});
};

function cadastrarComentario(id,valor ){
	requestAjax({url:'comentarioMarcador/cadastrarComentario',mapa:{id:id,comentario:$(valor).val()}}
		,function(data){
		$('#comentarios-list > tbody:last').append(data);
		$(valor).val('');
	});
}

function removerComentario(id){
	requestAjax({url:'comentarioMarcador/removerComentario',mapa:{id:id}},function(data){
		$('#indicador-comentario'+id).remove();
	});
}

function filtrarMarcadores(tipo, exibir){
	for(i = 0; i < markers.length; i++){
		if(markers[i].get('tipo') == tipo){
			markers[i].setVisible(exibir);
		}
	}
}

